/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.sales.hancadpe.client.view;

import br.com.sales.generics.client.components.mask.MaskTextFieldWidget;
import br.com.sales.generics.client.components.autocomplete.widget.Autocomplete;
import br.com.sales.generics.client.components.mask.MaskEditHandler;
import br.com.sales.generics.client.components.scroll.HScroll;
import br.com.sales.generics.client.components.timepicker.HDateTimePicker;
import br.com.sales.generics.client.presenter.events.ShowLoadingEvent;
import br.com.sales.generics.client.presenter.events.ShowLoadingHandler;
import br.com.sales.hancadpe.client.presenter.HanCadPEPresenter;
import br.com.sales.hancadpe.client.presenter.HanCadPEUiHanlder;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.CalendarUtil;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.ViewWithUiHandlers;
import java.util.Date;

/**
 *
 * @author v
 */
public class HanCadPEView extends ViewWithUiHandlers<HanCadPEUiHanlder>
        implements HanCadPEPresenter.Display, ShowLoadingHandler {

    private final static HanCadPEViewUiBinder uiBinder = GWT.create(HanCadPEViewUiBinder.class);
    private final HScroll mainContentScrollPanel = new HScroll();
    @UiField
    FlowPanel mainContentPanel;
    @UiField
    HTMLPanel container;
    @UiField
    TextBox dateEdit;
    @UiField
    TextBox nmPersonEdit;
    @UiField
    CheckBox isTipoPessoa;
    @UiField
    HDateTimePicker dateNascimentoEdit;
    @UiField
    MaskEditHandler cpfEdit;
    @UiField(provided = true)
    MaskTextFieldWidget rgEdit = new MaskTextFieldWidget("9.999.999-999");
    @UiField(provided = true)
    MaskTextFieldWidget nrTelefoneEdit = new MaskTextFieldWidget("(99)9999-9999");
    @UiField(provided = true)
    MaskTextFieldWidget nrCelularEdit = new MaskTextFieldWidget("(99)9999-9999");
    @UiField
    VerticalPanel paisEdit;
    @UiField
    VerticalPanel cidadeEdit;
    @UiField
    VerticalPanel estadoEdit;
    @UiField
    TextBox usuarioEdit;
    @UiField
    PasswordTextBox senhaEdit;
    @UiField
    Image loadingMessage;
    @UiField
    HTMLPanel detailPanel;
    @UiField
    Button cancelBtn;
    @UiField
    Button saveBtn;
    @UiField
    Button newBtn;
    @UiField
    Button gridDetailBtn;
    @UiField
    TextBox enderecoEdit;
    @UiField
    ListBox usuarioTipo;
    @UiField
    Label labelCpf;
    @UiField
    HDateTimePicker initialDate;
    @UiField
    HDateTimePicker finalDate;
    @UiField
    Image refreshBtn;
    @UiField
    TextBox filterName;
    @UiField
    HTMLPanel filterContainer;
    private Autocomplete countryComplete;
    private Autocomplete stateComplete;
    private Autocomplete cityComplete;
    @Inject
    private EventBus eventBus;

    @Inject
    public HanCadPEView() {
        container = uiBinder.createAndBindUi(this);
    }

    @Override
    public void build() {
        mainContentScrollPanel.setStyleName("container-product-scroll", true);
        countryComplete = Autocomplete.build()
                .setAttributeNameDesc("DS_PAIS")
                .setAttributeNameID("NR_SEQUENCIA")
                .setIsMultiValued(false)
                .setTableName("PAIS");
        paisEdit.add(countryComplete);
        stateComplete = Autocomplete.build()
                .setAttributeNameDesc("DS_ESTADO")
                .setAttributeNameID("NR_SEQUENCIA")
                .setIsMultiValued(false)
                .setTableName("ESTADO");
        estadoEdit.add(stateComplete);
        cityComplete = Autocomplete.build()
                .setAttributeNameDesc("DS_CIDADE")
                .setAttributeNameID("NR_SEQUENCIA")
                .setIsMultiValued(false)
                .setTableName("CIDADE");
        cidadeEdit.add(cityComplete);
        cityComplete.setReadOnly(true);
        stateComplete.setReadOnly(true);
        dateEdit.setEnabled(false);
        loadingMessage.setVisible(false);
        addEventHandler();
        adjustMaxLength();
        addItemListbox();
        refreshBtn.setResource(HanCadPEResources.INSTANCE.refresh());
        addId();
        adjustVisibilityIsFisicalPerson();
        setDateFilter();
        refreshBtn.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
                getUiHandlers().onClickRefreshBtn(event);
            }
        });
    }

    private void setDateFilter() {
        DateTimeFormat dtf = DateTimeFormat.getFormat("dd/MM/yyyy");
        Date data = new Date(System.currentTimeMillis());
        finalDate.setValue(dtf.format(data));
        CalendarUtil.addDaysToDate(data, -5);
        initialDate.setValue(dtf.format(data));
    }

    private void adjustVisibilityIsFisicalPerson() {
        isTipoPessoa.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {
                changeCpfEdit();
            }
        });
    }

    public void changeCpfEdit() {
        boolean isChecked = isTipoPessoa.getValue();
        cpfEdit.setIdField(isChecked ? "cpf" : "cnpj");
        labelCpf.setText(isChecked ? "CPF" : "CNPJ");
    }

    private void addId() {
        cpfEdit.getElement().setId("cpf");
    }

    private void addItemListbox() {
        usuarioTipo.addItem("...", "0");
        usuarioTipo.addItem("Gerente", "1");
        usuarioTipo.addItem("Cliente", "2");
        usuarioTipo.addItem("Fornecedor", "3");
        usuarioTipo.addItem("Atendente", "4");
    }

    private void adjustMaxLength() {
        nmPersonEdit.setMaxLength(255);
        usuarioEdit.setMaxLength(15);
        senhaEdit.setMaxLength(16);
        enderecoEdit.setMaxLength(350);
    }

    @Override
    public Widget asWidget() {
        return container;
    }

    private void addEventHandler() {
        eventBus.addHandler(ShowLoadingEvent.TYPE, this);
        countryComplete.addBlurHandler(new BlurHandler() {

            @Override
            public void onBlur(BlurEvent event) {
                stateComplete.setReadOnly(countryComplete.getValue() == null);
                stateComplete.setRestriction("AND NR_SEQ_PAIS = ?")
                        .setParameter(countryComplete.getValue());
            }
        });
        stateComplete.addBlurHandler(new BlurHandler() {

            @Override
            public void onBlur(BlurEvent event) {
                cityComplete.setReadOnly(stateComplete.getValue() == null);
                cityComplete.setRestriction("AND NR_SEQ_ESTADO = ?")
                        .setParameter(stateComplete.getValue());
            }
        });
        cpfEdit.addBlurHandler(new BlurHandler() {

            @Override
            public void onBlur(BlurEvent event) {
                getUiHandlers().validateCPF();
            }
        });
        rgEdit.addBlurHandler(new BlurHandler() {

            @Override
            public void onBlur(BlurEvent event) {
                getUiHandlers().validateCPF();
            }
        });

    }

    @Override
    public boolean isMandatory(Boolean isEditing) {
        boolean isMandatory = false;
        if (("".equals(nmPersonEdit.getText())
                || nmPersonEdit.getText() == null)
                && isEditing) {
            nmPersonEdit.getElement().addClassName("mandatory");
            isMandatory = true;
        } else {
            nmPersonEdit.getElement().removeClassName("mandatory");
        }
        if (("".equals(dateNascimentoEdit.getValueAsString())
                || dateNascimentoEdit.getValueAsString() == null)
                && isTipoPessoa.getValue()
                && isEditing) {
            dateNascimentoEdit.getElement().addClassName("mandatory");
            isMandatory = true;
        } else {
            dateNascimentoEdit.getElement().removeClassName("mandatory");
        }
        if (("".equals(cpfEdit.getValue())
                || cpfEdit.getValue() == null)
                && isEditing) {
            cpfEdit.getElement().addClassName("mandatory");
            isMandatory = true;
        } else {
            cpfEdit.getElement().removeClassName("mandatory");
        }
        if (("".equals(rgEdit.getValue())
                || rgEdit.getValue() == null)
                && isTipoPessoa.getValue()
                && isEditing) {
            rgEdit.getElement().addClassName("mandatory");
            isMandatory = true;
        } else {
            rgEdit.getElement().removeClassName("mandatory");
        }
        if (("".equals(enderecoEdit.getValue())
                || enderecoEdit.getValue() == null)
                && isEditing) {
            enderecoEdit.getElement().addClassName("mandatory");
            isMandatory = true;
        } else {
            enderecoEdit.getElement().removeClassName("mandatory");
        }
        if (("0".equals(usuarioTipo.getValue(usuarioTipo.getSelectedIndex()))
                || usuarioTipo.getValue(usuarioTipo.getSelectedIndex()) == null)
                && isEditing) {
            usuarioTipo.getElement().addClassName("mandatory");
            isMandatory = true;
        } else {
            usuarioTipo.getElement().removeClassName("mandatory");
        }
        return isMandatory;
    }

    @Override
    public void setEnabled(boolean isNewrecord) {
        controlVisibleButton(isNewrecord);
        setFieldsEnabled(isNewrecord);
    }

    public void setFieldsEnabled(boolean enabled) {
        nmPersonEdit.setEnabled(enabled);
        isTipoPessoa.setEnabled(enabled);
        cpfEdit.setEnabled(enabled);
        rgEdit.setEnabled(enabled);
        dateNascimentoEdit.setEnabled(enabled);
        nrTelefoneEdit.setEnabled(enabled);
        nrCelularEdit.setEnabled(enabled);
        countryComplete.setEnabled(enabled);
        stateComplete.setEnabled(enabled);
        cityComplete.setEnabled(enabled);
        enderecoEdit.setEnabled(enabled);
        usuarioTipo.setEnabled(enabled);
        usuarioEdit.setEnabled(enabled);
        senhaEdit.setEnabled(enabled);
    }

    @Override
    public void controlVisibleButton(boolean isNewrecord) {
        cancelBtn.setVisible(isNewrecord);
        saveBtn.setVisible(isNewrecord);
        newBtn.setVisible(!isNewrecord);
        gridDetailBtn.setVisible(!isNewrecord);
    }

    private void setMainContentScroll(IsWidget content) {
        mainContentScrollPanel.clear();
        mainContentPanel.clear();

        if (content != null) {
            mainContentScrollPanel.add(content);
            mainContentPanel.add(mainContentScrollPanel);
        }
    }

    @Override
    public void setInSlot(Object slot, IsWidget content) {
        if (slot == HanCadPEPresenter.HANCADPE_SLOT_TYPE) {
            setMainContentScroll(content);
        }
    }

    @Override
    public void showLoading(boolean show) {
        loadingMessage.setVisible(show);
    }

    @UiHandler("saveBtn")
    public void onClickSave(ClickEvent event) {
        getUiHandlers().onClickSave(event);
    }

    @UiHandler("newBtn")
    public void onClickNew(ClickEvent event) {
        getUiHandlers().onClickNew(event);
    }

    @UiHandler("cancelBtn")
    public void onClickCancel(ClickEvent event) {
        getUiHandlers().onClickCancel(event);
    }

    @UiHandler("gridDetailBtn")
    public void onClickGridDetail(ClickEvent event) {
        getUiHandlers().onClickGridDetail(event);
    }

    @Override
    public Autocomplete getStateComplete() {
        return stateComplete;
    }

    @Override
    public HDateTimePicker getDateNascimentoEdit() {
        return dateNascimentoEdit;
    }

    @Override
    public TextBox getEnderecoEdit() {
        return enderecoEdit;
    }

    @Override
    public Image getLoadingMessage() {
        return loadingMessage;
    }

    @Override
    public CheckBox getIsTipoPessoa() {
        return isTipoPessoa;
    }

    @Override
    public ListBox getUsuarioTipo() {
        return usuarioTipo;
    }

    @Override
    public TextBox getNmPersonEdit() {
        return nmPersonEdit;
    }

    @Override
    public HScroll getMainContentScrollPanel() {
        return mainContentScrollPanel;
    }

    @Override
    public FlowPanel getMainContentPanel() {
        return mainContentPanel;
    }

    @Override
    public TextBox getDateEdit() {
        return dateEdit;
    }

    @Override
    public MaskEditHandler getCpfEdit() {
        return cpfEdit;
    }

    @Override
    public MaskTextFieldWidget getRgEdit() {
        return rgEdit;
    }

    @Override
    public MaskTextFieldWidget getNrTelefoneEdit() {
        return nrTelefoneEdit;
    }

    @Override
    public MaskTextFieldWidget getNrCelularEdit() {
        return nrCelularEdit;
    }

    @Override
    public VerticalPanel getPaisEdit() {
        return paisEdit;
    }

    @Override
    public TextBox getUsuarioEdit() {
        return usuarioEdit;
    }

    @Override
    public TextBox getSenhaEdit() {
        return senhaEdit;
    }

    @Override
    public HTMLPanel getDetailPanel() {
        return detailPanel;
    }

    @Override
    public Autocomplete getCountryComplete() {
        return countryComplete;
    }

    @Override
    public Autocomplete getCityComplete() {
        return cityComplete;
    }

    @Override
    public HDateTimePicker getInitialDate() {
        return initialDate;
    }

    public void setInitialDate(HDateTimePicker initialDate) {
        this.initialDate = initialDate;
    }

    @Override
    public HDateTimePicker getFinalDate() {
        return finalDate;
    }

    public void setFinalDate(HDateTimePicker finalDate) {
        this.finalDate = finalDate;
    }

    @Override
    public TextBox getFilterName() {
        return filterName;
    }

    public void setFilterName(TextBox filterName) {
        this.filterName = filterName;
    }

    public Image getRefreshBtn() {
        return refreshBtn;
    }

    public void setRefreshBtn(Image refreshBtn) {
        this.refreshBtn = refreshBtn;
    }

    @Override
    public HTMLPanel getFilterContainer() {
        return filterContainer;
    }

    interface HanCadPEViewUiBinder extends UiBinder<HTMLPanel, HanCadPEView> {
    }
}
